<template>
  <PageWrapper dense contentFullHeight fixedHeight>
    <BasicTable @register="registerTable">
      <template #form-classifyId="{ model, field }">
        <a-select v-model:value="model[field]" :options="options" placeholder="请选择"
          :fieldNames="{ label: 'classifyName', value: 'classifyId' }" />
      </template>
      <template #toolbar>
        <a-button type="primary" @click="handleCreate">新增</a-button>
        <a-button type="primary" :disabled="selectedRowKeys.length === 0" @click="handleBatchDelete">批量删除</a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction :actions="createActions(record)" />
        </template>
      </template>
    </BasicTable>
    <ModalAddRecord @register="registerModal" @success="handleSuccess" />
  </PageWrapper>
</template>
<script setup lang="ts">
import { PageWrapper } from '@/components/Page'
import { BasicTable, useTable, TableAction, EditRecordRow, ActionItem } from '@/components/Table'
import {
  recordMonthDataList,
  recordMonthDataUpdate,
  recordMonthDataDelete,
} from '@/api/sys/manualEntry'
import { searchFormSchema, tableColumns } from './data'
import { ref, createVNode, onMounted } from 'vue'
import { useModal } from '@/components/Modal'
import { cloneDeep, last } from 'lodash-es'
import { useMessage } from '@/hooks/web/useMessage'
import { message, Modal } from 'ant-design-vue'
import { Key } from 'ant-design-vue/es/table/interface'
import ModalAddRecord from './ModalAddRecord.vue'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue'
import dayjs from 'dayjs'
import { getDictListByCodeAndName } from '@/api/sys/dict'
import { getClassifyTreeByPatent } from '@/api/collection/classify'


defineOptions({ name: 'ManualEntry' })
const { createMessage: msg } = useMessage()
const currentEditKeyRef = ref('')
const selectedRowKeys = ref<Key[]>([])
const options = ref([])

const [registerTable, { setColumns, setTableData, updateTableDataRecord, getForm }] = useTable({
  title: '动力用量及费用',
  // rowKey: 'id',
  columns: [],
  useSearchForm: true,
  formConfig: {
    labelWidth: 80,
    schemas: searchFormSchema,
    autoSubmitOnEnter: true,
    submitFunc: () => getTableData()
    // showResetButton: false
  },
  bordered: true,
  striped: true,
  pagination: false,
  actionColumn: {
    width: 120,
    title: '操作',
    dataIndex: 'action',
  },
  immediate: false,
  rowSelection: {
    onChange: (selectedKeys, selectedData) => {
      selectedRowKeys.value = selectedData.map((item) => item.id)
    },
  },
})
const [registerModal, { openModal }] = useModal()

function createActions(record: EditRecordRow): ActionItem[] {
  console.log(record, 'record')
  if (!record.editable) {
    return [
      {
        label: '编辑',
        disabled: record.disable || currentEditKeyRef.value ? currentEditKeyRef.value !== record.id : false,
        ifShow: record.tag != '合计',
        onClick: handleEdit.bind(null, record),
      },
      {
        label: '删除',
        color: 'error',
        ifShow: record.tag != '合计',
        disabled: currentEditKeyRef.value ? currentEditKeyRef.value !== record.id : false,
        popConfirm: {
          title: '确认删除',
          confirm: handleDelete.bind(null, record),
        },
      },
    ]
  }
  return [
    {
      label: '保存',
      onClick: handleSave.bind(null, record),
    },
    {
      label: '取消',
      onClick: handleCancel.bind(null, record),
    },
  ]
}

const formatHeader = (headerData) => {
  const headerList = headerData.map((item) => ({
    title: item,
    dataIndex: ['deviceCustomDataVal', item, 'incrementValue'],
    width: 120,
    editRow: true,
    editComponent: 'InputNumber',
    editRender: ({ text }) => {
      return text === null ? '--' : text
    },
  }))
  headerList.unshift({
    title: '标签名',
    dataIndex: 'tag',
    width: 170,
    fixed: 'left',
  })

  setColumns(headerList)
}

onMounted(() => {
  getOptions()
})

const getTableData = async () => {
  const {type, startDate, endDate} = getForm().getFieldsValue()
  const params = {
    type,
    years: [startDate, endDate],
  }
  const data = await recordMonthDataList(params)
  tableColumns[0].customCell = (_, _index:number) => {
    let col = { }
    let colSpan = 1
    let rowSpan = 1
      if (
        _index > 0 &&
        data[_index - 1]['tag'] &&
        _['tag'] === data[_index - 1]['tag']
      ) {
        rowSpan = 0 // 返回0表示在有跨度的行中不需要渲染，如果不为0，会被跨度合并时挤出到其他列显示
      } else {
        let total = 1
        if (_['tag']) {
          data.some((currentValue, index) => {
            if (index > _index) {
              if (currentValue['tag'] === _['tag']) {
                total++
                return false
              } else {
                return true
              }
            }
          })
        } else {
          total = 1
        }
        rowSpan = total
      }
    col = { rowSpan, colSpan }
    return col
  }
  tableColumns[2].customCell = (_, _index:number) => {
    let col = { }
    let colSpan = 1
    let rowSpan = 1
      if (
        _index > 0 &&
        data[_index - 1]['tag'] &&
        _['tag'] === data[_index - 1]['tag']
      ) {
        rowSpan = 0 // 返回0表示在有跨度的行中不需要渲染，如果不为0，会被跨度合并时挤出到其他列显示
      } else {
        let total = 1
        if (_['tag']) {
          data.some((currentValue, index) => {
            if (index > _index) {
              if (currentValue['tag'] === _['tag']) {
                total++
                return false
              } else {
                return true
              }
            }
          })
        } else {
          total = 1
        }
        rowSpan = total
      }
    col = { rowSpan, colSpan }
    return col
  }
  setColumns(tableColumns)
  setTableData(data)
}
const getOptions = async () => {
  const parentData = await getDictListByCodeAndName({
    code: 'budget_manage',
    itemName: '动力费用',
  })
  const data = await getClassifyTreeByPatent({ parentClassifyId: parentData.itemCode })
  options.value = data[0].children
  await getForm().setFieldsValue({
    type: options.value[0].classifyId
  })
  getTableData()
}

const handleCancel = (record: EditRecordRow) => {
  currentEditKeyRef.value = ''
  record.onEdit?.(false, false)
}

const handleEdit = (record) => {
  console.log(record);
  if (record.tag !== '合计') {
    currentEditKeyRef.value = record.key
    record.onEdit?.(true)
    console.log(record.onEdit?.(true));
  }
}


const handleSave = async (record) => {
  // 校验
  const valid = await record.onValid?.()
  if (valid) {
    const editData = cloneDeep(record.editValueRefs)!
    const data = {
      id: record.id,
      ...editData,
      year: record.year,
      tag: record.tag,
      type: record.type
    }
    await recordMonthDataUpdate(data)
    const pass = await record.onEdit?.(false, true)
    if (pass) {
      currentEditKeyRef.value = ''
    }
    msg.success({ content: '数据已保存', key: 'saving' })
    getTableData()
  } else {
    msg.error({ content: '请填写正确的数据', key: 'saving' })
  }
}

const handleBatchDelete = () => {
  Modal.confirm({
    title: '提示',
    icon: createVNode(ExclamationCircleOutlined),
    content: '确认删除吗？',
    onOk() {
      deleteFn(selectedRowKeys.value, true)
    },
    onCancel() {
      return
    },
  })
}

const handleDelete = (record) => {
  deleteFn([record.id])
}

const deleteFn = (ids, isBatch = false) => {
  recordMonthDataDelete({
    ids,
  }).then((res) => {
    message.success('删除成功')
    getTableData()
    if (isBatch) {
      selectedRowKeys.value = []
    }
  })
}

const handleCreate = () => {
  openModal(true, {
    isUpdate: false,
  })
}
// 添加成功
const handleSuccess = ({ isUpdate, values }) => {
  if (isUpdate) {
    // 演示不刷新表格直接更新内部数据。
    // 注意：updateTableDataRecord要求表格的rowKey属性为string并且存在于每一行的record的keys中
    const result = updateTableDataRecord(values.id, values)
    console.log(result)
  } else {
    getTableData()
  }
}
</script>
<style scoped lang="scss">
:deep(.ant-input-number) {
  min-width: 80px;
}
</style>
